package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.injector.methods.SelectList;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 商家分类缓存
     * @return
     */
    public Result queryTypeList() {
       //先查看redis中是否存在缓存
        String key = "cache:type:";
        List<ShopType>ShopTypeList=new ArrayList<>();
        for (int i = 1; i <=10; i++) {
            String type = stringRedisTemplate.opsForValue().get(key+i);
            if (type!=null){
                //存在，将json格式转成ShopType对象返回
                ShopType shopType = JSONUtil.toBean(type, ShopType.class);
                ShopTypeList.add(shopType);
                if (i==10){
                    return Result.ok(ShopTypeList);

                }
            }
        }


        //不存在去数据库里面找
        List<ShopType> shopTypes = list();
        for (ShopType shopType : shopTypes) {
            //将shopType转成json
            String shopTypeJson = JSONUtil.toJsonStr(shopType);
            //将json存入redis
            stringRedisTemplate.opsForValue().set(key+shopType.getId(),shopTypeJson);
        }
        return Result.ok(shopTypes);

    }
}
